package com.qimei.onerice.servlet;

import com.qimei.onerice.entity.Order;
import com.qimei.onerice.entity.OrderDetail;
import com.qimei.onerice.service.OrderDetailService;
import com.qimei.onerice.service.OrderService;
import com.qimei.onerice.service.impl.OrderDetailServiceImpl;
import com.qimei.onerice.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/quantity")
public class QuantityServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		// 获取前端传递的参数
		String orderDetailId = request.getParameter("orderDetailId");
		String action = request.getParameter("action");

		OrderDetailService orderDetailService = new OrderDetailServiceImpl();
		OrderService orderService = new OrderServiceImpl();
		OrderDetail newOrderDetail = orderDetailService.getOrderDetailById(Integer.parseInt(orderDetailId));
		Order newOrder = orderService.getOrderById(newOrderDetail.getOrderId());

		if ("add".equals(action)){
			// 增加数量

			newOrderDetail.setQuantity(newOrderDetail.getQuantity() + 1);
			newOrderDetail.setSubtotal(newOrderDetail.getQuantity() * newOrderDetail.getUnitPrice());
			orderDetailService.updateOrderDetail(newOrderDetail);

			newOrder.setTotalAmount(newOrder.getTotalAmount() + newOrderDetail.getUnitPrice());
			orderService.updateOrder(newOrder);
		} else {
			// 减少数量
			if (newOrderDetail.getQuantity() > 1) {
				// 数量大于1才能继续减少

				newOrderDetail.setQuantity(newOrderDetail.getQuantity() - 1);
				newOrderDetail.setSubtotal(newOrderDetail.getQuantity() * newOrderDetail.getUnitPrice());
				orderDetailService.updateOrderDetail(newOrderDetail);

				newOrder.setTotalAmount(newOrder.getTotalAmount() - newOrderDetail.getUnitPrice());
				orderService.updateOrder(newOrder);
			}
		}

		request.getRequestDispatcher("/view/cart.jsp").forward(request, response);
	}
}
